# -*- coding: utf-8 -*-
import re

from ustv.models import TVideoList, TTvEpisodePlot, TUrlList, TSpiderVideoIndex
from ustv.common import Codes, Utils
from django.db.models import Q

import logging
logger = logging.getLogger('django')

class TV_Series:
    def queryByTitle(self, title):
        if title is None:
            return Codes.PARAM_ERROR, u"参数错误", []

        videos = TVideoList.objects.filter(Q(title=title) | Q(alias__icontains=title))
        if len(videos) < 1:
            return Codes.NOT_FOUND, u"未收录", []

        return Codes.OK, "OK", []

    def queryBySeriesInfo(self, name, season):
        if name is None:
            return Codes.PARAM_ERROR, u"参数错误", []


        logger.debug("name=%s-%s" % (name,season))

        if season is None:
            videos = TVideoList.objects.filter(series_name=name)
        else:
            videos = TVideoList.objects.filter(series_name=name, series_no=season)
        if len(videos) < 1:
            return Codes.NOT_FOUND, u"未收录", []

        return Codes.OK, "OK", []

    def needCrawl(self, title, updatetip):
        if title is None or updatetip is None:
            return Codes.NOT_FOUND, "not found", []

        print updatetip
        episode = Utils.extract_keywords(updatetip, ur"\D*(\d+)集")
        if Utils.str_is_num(episode):
            episode_cnt = int(episode)
        else:
            episode_cnt = 0

        logger.debug("episode_cnt=%s" % (episode_cnt,))

        videos = TVideoList.objects.filter(title=title)
        if len(videos) < 1:
            return Codes.NOT_FOUND, "not found", []

        plots = TTvEpisodePlot.objects.filter(lekuid=videos[0].lekuid)
        if len(plots) < episode_cnt:
            return Codes.PARTIAL, "plot partial", []

        urls = TUrlList.objects.filter(title=title)
        if len(urls) < episode_cnt:
            return Codes.URL_PARTIAL, "url partial", []

        return Codes.OK, "OK", []

    def takeTask(self):
        TSpiderVideoIndex.objects.filter()
